package priv.menghan.happy.learning.common.handler;

import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;
import priv.menghan.happy.learning.common.exception.BusinessException;
import priv.menghan.happy.learning.common.exception.ResourceNotFoundException;
import priv.menghan.happy.learning.common.rsp.Response;

import java.time.LocalDateTime;
import java.util.stream.Collectors;

/**
 * 全局异常处理器
 *
 * @author Monika
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理自定义业务异常
     */
    @ExceptionHandler(BusinessException.class)
    public ResponseEntity<Response<?>> handleBusinessException(BusinessException ex, WebRequest request) {
        return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                .body(Response.fail(HttpStatus.BAD_REQUEST.value(), ex.getMessage()));
    }

    /**
     * 处理请求参数校验失败异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<Response<?>> handleValidationExceptions(MethodArgumentNotValidException ex, WebRequest request) {
        String errorMessage = ex.getBindingResult().getAllErrors().stream()
                .map(DefaultMessageSourceResolvable::getDefaultMessage)
                .collect(Collectors.joining(", "));
        return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                .body(Response.fail(HttpStatus.BAD_REQUEST.value(), "参数校验失败: " + errorMessage));
    }

    /**
     * 处理资源未找到异常（如用户不存在）
     */
    @ExceptionHandler(ResourceNotFoundException.class)
    public ResponseEntity<Response<?>> handleResourceNotFoundException(ResourceNotFoundException ex, WebRequest request) {
        return ResponseEntity.status(HttpStatus.NOT_FOUND)
                .body(Response.fail(HttpStatus.NOT_FOUND.value(), ex.getMessage()));
    }

    /**
     * 处理系统内部错误
     */
    @ExceptionHandler(Exception.class)
    public ResponseEntity<Response<?>> handleGeneralException(Exception ex, WebRequest request) {
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body(Response.fail(HttpStatus.INTERNAL_SERVER_ERROR.value(),
                        "系统内部错误：" + ex.getMessage()));
    }

    /**
     * 可选：记录日志的方法
     */
    private void logError(Exception ex, HttpStatus status, WebRequest request) {
        // 这里可以替换为真正的日志记录逻辑（如使用 Slf4j）
        System.err.println(LocalDateTime.now() + " | " + status + " | " + ex.getMessage() + " | " + request.getDescription(false));
    }
}
